package com.dabai.dbutils.utils.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.CRC32;

/**
 * Description : Other
 *
 * @author BAI
 */
public class Crc32Utils {

    /**
     * 得到crc32
     * 字符串CRC32校验
     *
     * @param value 价值
     * @return {@link String}
     */
    public static String getCRC32(String value) {
        CRC32 crc32 = new CRC32();
        crc32.update(value.getBytes());
        return String.valueOf(crc32.getValue());
    }

    /**
     * 得到crc32按文件
     * 校验文件的CRC32值
     *
     * @param file 文件
     * @return {@link String}
     */
    public static String getCRC32ByFile(File file) {
        CRC32 crc32 = new CRC32();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                crc32.update(buffer, 0, length);
            }
            return String.valueOf(crc32.getValue());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
